﻿/// <reference path="../tiny_mce/tiny_mce_popup.js" />
/// <reference path="jquery-1.4.4-vsdoc.js" />

(function ($) {
    $.extend({
        FlexExplorer: {

            returnOpenerId: null,
            openerCallback: null,
            lastPathCookie: '__Flex_LAST_PATH',

            Flash: {
                swf: 'BasicFM.swf',
                attributes: {},
                params: {
                    wmode: 'transparent',
                    quality: 'best',
                    width: "100%",
                    height: "100%"

                },
                flashvars: {
                    focusPath: '',
                    sessionId: '',
                    returnFull: 1

                }
            },

            String: {
                trim: function () {
                    return this.replace(/^\s+|\s+$/g, '');

                },

                //if( $.StringEx.isNullOrEmpty('') ) alert('Empty string');
                isNullOrEmpty: function (value) {
                    if (value) {
                        if (typeof (value) == 'string') {
                            if (value.length > 0)
                                return false;
                        }
                        if (value != null)
                            return false;
                    }
                    return true;

                },

                replace: function (source, oldVal, newVal) {
                    var result = source;
                    //result = result.replace(oldVal, newVal);
                    result = result.replace(new RegExp(oldVal, 'ig'), newVal);
                    //result = result.replace(new RegExp('\\' + oldVal + '\\', 'g'), newVal);

                    return result;
                },

                //alert( $.StringEx.format("Hello {0}.","Nasa8x") );
                format: function (format, args) {
                    var result = format;
                    for (var i = 1; i < arguments.length; i++) {
                        result = result.replace(new RegExp('\\{' + (i - 1) + '\\}', 'g'), arguments[i]);
                    }
                    return result;
                },
                startsWith: function (prefix, ignoreCase) {
                    if (!prefix) return false;
                    if (prefix.length > this.length) return false;
                    if (ignoreCase) {
                        if (ignoreCase == true) {
                            return (this.substr(0, prefix.length).toUpperCase() == prefix.toUpperCase());
                        }
                    }
                    return (this.substr(0, prefix.length) === prefix);
                },
                endsWith: function (suffix, ignoreCase) {
                    if (!suffix) return false;
                    if (suffix.length > this.length) return false;
                    if (ignoreCase) {
                        if (ignoreCase == true) {
                            return (this.substr(this.length - suffix.length).toUpperCase() == suffix.toUpperCase());
                        }
                    }
                    return (this.substr(this.length - suffix.length) === suffix);
                }
            },


            getParentWin: function () {
                var w = opener || parent || top;
                return w != window ? w : null;
            },

            getWin: function () {
                return (!window.frameElement && window.dialogArguments) || opener || parent || top;
            },
            getWindowArg: function (c, b) {
                var a = this.params[c];
                return $.is(a) ? a : b;
            },

            cookie: function (key, value, options) {

                // key and at least value given, set cookie...
                //https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
                /** @example $.cookie('the_cookie', 'the_value');
                * @desc Set the value of a cookie.
                * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
                * @desc Create a cookie with all available options.
                * @example $.cookie('the_cookie', 'the_value');
                * @desc Create a session cookie.
                * @example $.cookie('the_cookie', null);
                * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
                * used when the cookie was set.
                */
                if (arguments.length > 1 && String(value) !== "[object Object]") {
                    options = $.extend({}, options);

                    if (value === null || value === undefined) {
                        options.expires = -1;
                    };

                    if (typeof options.expires === 'number') {
                        var days = options.expires, t = options.expires = new Date();
                        t.setDate(t.getDate() + days);
                    };

                    if (typeof options.days === 'number') {
                        var date = new Date();
                        date.setTime(date.getTime() + (options.days * 24 * 60 * 60 * 1000));
                        options.expires = date;
                    }


                    value = String(value);

                    return (document.cookie = [
                        encodeURIComponent(key), '=',
                        options.raw ? value : encodeURIComponent(value),
                        options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                        options.path ? '; path=' + options.path : '',
                        options.domain ? '; domain=' + options.domain : '',
                        options.secure ? '; secure' : ''
                    ].join(''));
                };

                // key and possibly options given, get cookie...
                options = value || {};
                var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
                return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
            },

            dateFormat: function (date, f) {


                var d = date;

                return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
                    function ($1) {
                        switch ($1.toLowerCase()) {
                            case 'yyyy': return d.getFullYear();
                            case 'mmmm': return gsMonthNames[d.getMonth()];
                            case 'mmm': return gsMonthNames[d.getMonth()].substr(0, 3);
                            case 'mm': return ((d.getMonth() + 1) > 10) ? (d.getMonth() + 1) : "0" + (d.getMonth() + 1);
                            case 'dddd': return gsDayNames[d.getDay()];
                            case 'ddd': return gsDayNames[d.getDay()].substr(0, 3);
                            case 'dd': return (d.getDate() > 10) ? d.getDate() : "0" + d.getDate();
                            case 'hh':
                                var h;
                                return ((h = d.getHours() % 12) ? h : 12);
                            case 'nn': return d.getMinutes();
                            case 'ss': return d.getSeconds();
                            case 'a/p': return d.getHours() < 12 ? 'a' : 'p';
                        }
                        return d.getUTCDate();
                    });

            },

            rememberLastPath: function (_val) {
                this.cookie(this.lastPathCookie, _val, { days: 0.5 });
            },

            getQueryString: function (key) {
                key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var regex = new RegExp("[\\?&]" + key + "=([^&#]*)", 'ig');
                var qs = regex.exec(window.location.href);
                if (qs == null)
                    return null;
                else
                    return qs[1];

            },

            convertFromUnixTimestamp: function (s) {
                var _d = new Date();
                _d.setTime(s * 1000);

                return _d;
            },

            convertToUnixTimestamp: function (date) {
                return date.getTime() / 1000;
            },

            getFilePath: function (_file) {
                return _file.substring(0, _file.lastIndexOf('/'));
            },

            getFileName: function (_file) {
                return _file.substring(0, _file.lastIndexOf('.'));
            },

            getFocusPath: function () {

                var _target = this.getQueryString('target');
                if (!this.String.isNullOrEmpty(_target)) {
                    if (_target.indexOf("/") != -1) {

                        return this.getFilePath(_target);

                    } else if (_target.indexOf(".") != -1) {

                        var _date = this.convertFromUnixTimestamp(this.getFileName(_target));

                        if (_date) {
                            return this.dateFormat(_date, "yyyy/mm/dd");
                        }

                    }
                }

                var _folder = this.cookie(this.lastPathCookie);
                if (!this.String.isNullOrEmpty(_folder)) {
                    return _folder;
                };
                return '';

            },

            insert: function (_val) {

                var url = _val;
                var win = this.getWin();

                var args = window.dialogArguments;

                if (args) {

                    if (args.returnId) {
                        win.document.getElementById(args.returnId).value = url;

                    }
                    else if (args.callback) {

                        args.files = _val;
                        args.callback.call(win, args);

                    }


                   // alert(args + '-' + args.callback);

                    self.close();
                    
                    return true;

                }
                else if (tinymce) { // Plugin TinyMce 


                    var _ed = tinyMCEPopup.getWindowArg("editor");
                    if (_ed) {

                        //_callback.call(win, url);

                        var _imgs = _val.split(';');

                        $.each(_imgs, function (index, value) {
                            _ed.execCommand('mceInsertContent', false, '<img src="' + value + '" /><br/><br/>');
                        });

                    };

                    win = tinyMCEPopup.getWindowArg("window");
                    var returnId = tinyMCEPopup.getWindowArg("input");
                    if (returnId != null) {
                        // insert information now
                        win.document.getElementById(returnId).value = url;
                    };

                    if (typeof (win.ImageDialog) != 'undefined') {
                        // for image browsers: update image dimensions
                        if (win.ImageDialog.getImageData) {
                            win.ImageDialog.getImageData();
                        }
                        // show preview image
                        if (win.ImageDialog.showPreviewImage) {
                            win.ImageDialog.showPreviewImage(url);
                        }
                    };

                    // close popup window
                    tinyMCEPopup.close();
                }

                else if (navigator.appName.indexOf('Microsoft') != -1) {
                    window.returnValue = url;
                    self.close();
                }

                return false;

            },

            createFlash: function (_w, _h) {
                swfobject.embedSWF(this.Flash.swf, "_flashPanel", _w, _h, "9.0.0", false, this.Flash.flashvars, this.Flash.params, this.Flash.attributes);
            },

            onLoad: function () {

                this.returnOpenerId = this.getQueryString("returnId");
                this.Flash.flashvars.focusPath = this.getFocusPath();
                this.Flash.flashvars.returnFull = this.getQueryString("returnFull");
                this.createFlash($(window).width(), $(window).height());

            }

            // add more function

        }// end Nasa8x
    });   // end extend

})(jQuery);


$(document).ready(function () {
    $.FlexExplorer.onLoad();

    $(window).bind('resize', function () {

        $("#_flashPanel").width($(window).width()).height($(window).height());

    });
});




